package com.longrise.android.byjk.plugins.course.pay;


import android.app.Activity;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.app.BYJKAppLike;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.CourseDetailEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.eventbean.PayEventBean;
import com.longrise.common.utils.DZZWTools;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by callxkj on 2017/11/19.
 * 支付页面 与 批量购买
 */

public class PaymentPresenter extends PaymentContract.Presenter {

    private EntityBean[] mOpenResults;
    private IWXAPI mWxapi;

    private int mOnError = 0;       //调用失败次数   最高3次
    private int mSleepTime = 3000; //延时调用时间
    private String out_trade_no;


    @Override
    protected void init() {
        mWxapi = BYJKAppLike.mIWXAPI;
        EventBus.getDefault().register(this);
    }

    /**
     * 批量开通培训
     *
     * @param courseids 课程id的集合
     */
    @Override
    public void openLotsOfTrain(ArrayList<String> courseids) {
        EntityBean bean = new EntityBean();
        bean.set("courseids", courseids);
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        mView.showNormalLoadingPage();
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                "bbt_course_openLotsOfTrainForApp", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            if (result != null) {
                                EntityBean bean = (EntityBean) result;
                                int resultstate = bean.getInt("resultstate");
                                if (resultstate == 1) {
                                    EntityBean resultBean = bean.getBean("result");
                                    mOpenResults = bean.getBeans("result");
                                    mView.showContentPage();
                                } else {
                                    mView.showToast(bean.getString("resultdesc"));
                                    mView.showContentPage();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            mView.showNonNetPage();
                        }
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        mView.showNonNetPage();
                    }

                    @Override
                    public void onFinished(String key, String service) {

                    }
                });
    }

    //微信支付
    @Override
    public void toWxpay(int buytype) {
        String userid = UserInfor.getInstance().getUserid(); // 用户id
        String userName = UserInfor.getInstance().getPersonname();
        EntityBean bean = new EntityBean();
        bean.set("trainsignups", mOpenResults); //开通课程返回的结果
        bean.set("userid", userid);
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("buytype", buytype);
        bean.set("username", userName);
        bean.set("yue", 0);
        bean.set("os_type", "ANDROID");
        bean.set("IOS_edition", 1);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        mView.showLoadingDialog();
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_pay_WChatPay2Batch",
                fbean, new LoadDataManager.OnRequestCallListener() {

                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            DZZWTools.dismissDialog(null);
                            EntityBean bean = (EntityBean) result;
                            int resultstate = (Integer) bean.get("resultstate");
                            String resultdesc = bean.getString("resultdesc");
                            if (resultstate == 200) {
                                EntityBean resultbean = bean.getBean("result");
                                out_trade_no = resultbean.getString("out_trade_no");
                                PayReq req = new PayReq();
                                req.appId = (String) resultbean.get("appid");
                                req.nonceStr = (String) resultbean.get("noncestr");
                                req.packageValue = (String) resultbean.get("package");
                                req.partnerId = (String) resultbean.get("partnerid");
                                req.prepayId = (String) resultbean.get("prepayid");
                                req.sign = (String) resultbean.get("sign");
                                req.timeStamp = String.valueOf(resultbean.getLong("timestamp"));
                                boolean wxAppInstalled = mWxapi.isWXAppInstalled();
                                if (wxAppInstalled) {
                                    boolean sendReq = mWxapi.sendReq(req);
                                } else {
                                    DZZWTools.showToast(mContext, mContext.getResources().getString(R.string.wx_not_installed), 0);
                                }
                            } else {
                                if ("您已购买该培训计划".equals(resultdesc)) {
                                    CourseDetailEvent event = new CourseDetailEvent();
                                    event.setCourseBuyStatus(true);
                                    EventBus.getDefault().post(event);
                                    DZZWTools.showToast(mContext, resultdesc, 0);
                                } else {
                                    mView.showWxPayErrorDialog();
                                }
                            }
                        } catch (Exception e) {
                            DZZWTools.showToast(mContext, "支付失败", 0);
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        DZZWTools.showToast(mContext, "支付失败", 0);
                    }
                });
    }

    /**
     * 支付宝支付
     *
     * @param buytype 购买途径 1-单个购买 2-批量购买 3- 团购
     */
    @Override
    public void toAlipay(int buytype) {
        String userid = UserInfor.getInstance().getUserid(); // 用户id
        String userName = UserInfor.getInstance().getPersonname();
        EntityBean bean = new EntityBean();
        bean.set("trainsignups", mOpenResults); //开通课程返回的结果
        bean.set("userid", userid);
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        bean.set("buytype", buytype);
        bean.set("username", userName);
        bean.set("yue", 0);
        bean.set("os_type", "ANDROID");
        bean.set("IOS_edition", 1);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        mView.showLoadingDialog();
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_pay_getAlipayPayUrl2Batch",
                fbean, new LoadDataManager.OnRequestCallListener() {

                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            EntityBean bean = (EntityBean) result;
                            int resultstate = (Integer) bean.get("resultstate");
                            String resultdesc = bean.getString("resultdesc");
                            if (resultstate == 200) {
                                EntityBean msresult = bean.getBean("result");
                                out_trade_no = msresult.getString("out_trade_no");
                                final String payInfo = msresult.getString("url");
                                Runnable payRunnable = new Runnable() {
                                    @Override
                                    public void run() {
                                        // 构造PayTask 对象
                                        PayTask alipay = new PayTask((Activity) mContext);
                                        // 调用支付接口，获取支付结果
                                        String result = alipay.pay(payInfo, true);
                                        parseAliResult(result);

                                    }
                                };

                                // 必须异步调用
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();
                            } else {
                                if ("您已购买该培训计划".equals(resultdesc)) {
                                    CourseDetailEvent event = new CourseDetailEvent();
                                    event.setCourseBuyStatus(true);
                                    EventBus.getDefault().post(event);
                                    DZZWTools.showToast(mContext, resultdesc, 0);
                                } else {
                                    mView.showAliPayErrorDialog();
                                }
                            }
                        } catch (Exception e) {
                            DZZWTools.showToast(mContext, "支付失败", 0);
                        }
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        DZZWTools.showToast(mContext, "支付失败", 0);
                    }
                });
    }

    /**
     * 解析支付宝返回的数据
     */
    private void parseAliResult(final String result) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                e.onNext(result);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRxManager.addDisposable(d);
                    }

                    @Override
                    public void onNext(String value) {
                        PayResult payResult = new PayResult(value);
                        /**
                         * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                         * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                         * docType=1) 建议商户依赖异步通知
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            mView.showNotBackWaitDialog();
                            toConfirmPayresult(out_trade_no);
                        } else {
                            mView.showAliPayErrorDialog();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        DZZWTools.showToast(mContext, "支付失败", 0);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 数据库查询支付宝 微信是否支付成功
     */
    @Override
    public void toConfirmPayresult(String out_trade_no) {
        EntityBean bean = new EntityBean();
        bean.set("out_trade_no", out_trade_no);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl,
                "bbt_pay_getAliPayResult", fbean, new LoadDataManager.OnRequestCallListener() {

                    private boolean paysuccess = false;

                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        paysuccess = true;
                        parseResult(result);
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        if (!paysuccess) {
                            DZZWTools.dismissNotBackDialog();
                        }

                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

                    }
                });

    }


    /**
     * 处理微信 支付宝 调用服务区查询是否支付成功的结果
     */
    private void parseResult(Object result) {
        try {
            EntityBean bean = (EntityBean) result;
            Integer resultstate = bean.getInt("resultstate");
            if (resultstate == 0) { // 0 支付失败
                if (mOnError < 3) {
                    sleep();
                } else {
                    //三次查询都是支付失败
                    mView.dismissNotBackDialog();
                    mView.showPayError();
                }

            } else if (resultstate == 1) { // 1 支付成功
                mView.dismissNotBackDialog();
                mView.showPaySuccess();
            }

        } catch (Exception e) {
            DZZWTools.dismissNotBackDialog();
            mView.showPayError();
        }
    }


    /**
     * 延迟发送请求
     */
    private void sleep() {
        mOnError++;  //不超过三次
        Observable.timer(mSleepTime, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRxManager.addDisposable(d);
                    }

                    @Override
                    public void onNext(Long value) {
                        toConfirmPayresult(out_trade_no);
                    }

                    @Override
                    public void onError(Throwable e) {
                        //与三次查询失败的处理方式一样
                        DZZWTools.dismissNotBackDialog();
                        mView.showPayError();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * eventbus接收 微信支付宝 支付的结果
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getPayResult(PayEventBean bean) {
        if (bean.isWxPaySuccess()) {
            mView.showNotBackWaitDialog();
            toConfirmPayresult(out_trade_no);
        }
    }

    @Override
    public void detachV() {
        super.detachV();
        EventBus.getDefault().unregister(this);
    }
}
